package com.vimi8.ebb.auth.configuration;

import com.vimi8.ebb.auth.model.DBUserDetails;
import com.vimi8.ebb.auth.service.DBUserDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * Created by Administrator on 2016/11/16.
 */
public class UserDetailsServiceImpl implements UserDetailsService {
    private Logger logger =  LoggerFactory.getLogger(this.getClass());
    private DBUserDetailsService dbUserDetailsService;

    public UserDetailsServiceImpl(DBUserDetailsService dbUserDetailsService){
        this.dbUserDetailsService=dbUserDetailsService;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        DBUserDetails user = null;
        try {
            user = dbUserDetailsService.getUserDetailsByPhoneNumber(username);
        }catch (Exception ex){
            logger.error(ex.getLocalizedMessage());
        }
        if(user==null){
            try {
                user = dbUserDetailsService.getUserDetailsByIdCard(username);
            }catch (Exception ex){
                logger.error(ex.getLocalizedMessage());
            }
        }
        if(user==null){
            try {
                user = dbUserDetailsService.getUserDetailsByUsername(username);
            }catch (Exception ex){
                logger.error(ex.getLocalizedMessage());
            }
        }
        if(user==null){
            throw new UsernameNotFoundException("invalid username or password");
        }
        if(!user.isAccountNonExpired()){
            throw new AccountExpiredException("invalid username or password");
        }
        if(!user.isAccountNonLocked() ){
            throw new LockedException("invalid username or password");
        }
        if( !user.isEnabled() ){
            throw new DisabledException("invalid username or password");
        }
        if(!user.isCredentialsNonExpired()){
            throw new CredentialsExpiredException("invalid username or password");
        }
        return user;
    }
}
